<?php
/**
 * @author Di Zhang <zhangdi_me@163.com>
 */

namespace yiizh\lepture\editor;


use yii\base\InvalidConfigException;
use yii\web\View;
use yii\helpers\Html;
use yii\widgets\InputWidget;

class Editor extends InputWidget
{
    public function init()
    {
        parent::init();
        if (!isset($this->id)) {
            throw new InvalidConfigException('请设置 [[id]] 属性.');
        }

        $this->options['id'] = $this->id;
        $this->registerClientScript();
    }

    /**
     * @inheritdoc
     */
    public function run()
    {
        if ($this->hasModel()) {
            echo Html::activeTextarea($this->model, $this->attribute, $this->options);
        } else {
            echo Html::textarea($this->name, $this->value, $this->options);
        }
        $this->registerClientScript();
    }

    public function registerClientScript(){
        LeptureEditorAsset::register($this->getView());
        $this->getView()->registerJs(<<<EOF
        $('#{$this->id}').ready(function(){new Editor().render();});
EOF
,View::POS_END);
    }
}